import { Injectable } from '@nestjs/common';
import { DbService } from '../../db/db.service';
import CreateDto from './dto/create.dto';
import * as dayjs from 'dayjs';
import UpdateDto from './dto/update.dto';
import { DeviceParamsField } from '@app/db/entity/DeviceParamsField';
import PageDto from './dto/page.dto';
import { FindOptionsWhere, Like } from 'typeorm';

@Injectable()
export class DeviceParamsFieldService {
    constructor(
        private readonly db:DbService
    ){}
    

    async options() {
        return this.db.deviceParamsField.find({enable : true}, {id : true, name : true})
    }

    async page(dto:PageDto) {
        let result:PaginationResult<DeviceParamsField> = {
            total : 0,
            rows : []
        }

        let where:FindOptionsWhere<DeviceParamsField> = {
        }
        if(dto.name) {
            where.name = Like('%' + dto.name + '%')
        }

        result.total = await this.db.deviceParamsField.count(where)

        if(result.total > 0) {
            result.rows = await this.db.deviceParamsField.pagination(dto.pageNo, dto.pageSize, where, null, {id : 'DESC'})
        }

        return result
    }

    
    async add(dto:CreateDto, memberId:number) {

        if(true == await this.db.deviceParamsField.isExistsByWhere({name : dto.name})) throw new Error('已存在相同的名称')
        if(true == await this.db.deviceParamsField.isExistsByWhere({key : dto.key})) throw new Error('已存在相同的参数名')

        return this.db.deviceParamsField.insert({...dto, creatorId : memberId, createTime : dayjs().unix()})
    }

    async update(dto:UpdateDto) {
        let fields = Object.keys(dto) as (keyof DeviceParamsField)[]
        if(fields.length == 0) return true

        const row = await this.db.deviceParamsField.findOne({ id : dto.id })
        
        if(!row) return false

        let updateData:KeyToValueType<DeviceParamsField> = {}

        for(let k in row) {
            if(k in dto) {
                if(k == 'options') {
                    if(JSON.stringify(dto.options) == JSON.stringify(row.options)) continue
                    
                }else {
                    if(row[k] == dto[k]) continue
                }
    
                updateData[k] = dto[k]
            }
            
        }

        if(Object.keys(updateData).length == 0) return true

        if(updateData.name && (true == await this.db.deviceParamsField.isExistsByWhere({name : dto.name}))) throw new Error('已存在相同的名称')
        if(updateData.key && (true == await this.db.deviceParamsField.isExistsByWhere({key : dto.key}))) throw new Error('已存在相同的参数名')
        
        updateData.updateTime = dayjs().unix()

        return this.db.deviceParamsField.update({id : dto.id}, updateData)
    }

    async del(id:number) {
        let row = await this.db.deviceParamsField.findOne({ id }, ['id'])
        if(!row) return
        return this.db.deviceParamsField.delete({id : id})
    }
}
